<?php

namespace App\Foundation\Rbac;

use Framework\Foundation\Database\FDB;

class UserRBAC
{
    public function hasPermission($userId, $permissionId)
    {
        $sql = "
            SELECT `permission_id` FROM `rbac_role_permissions`
            WHERE `role_id` IN(
              SELECT `role_id` FROM `rbac_user_roles` WHERE `user_id`=?
            ) AND `permission_id`=?
        ";

        $statement = FDB::getPdo()->prepare($sql);
        $statement->execute([$userId, $permissionId]);
        $ret = $statement->fetchAll(\PDO::FETCH_ASSOC);
        if (empty($ret)) {
            return false;
        }

        return true;
    }

    public function hasRole($userId, $roleId)
    {
        $ret = FDB::from('rbac_user_roles')
            ->where(['user_id' => $userId, 'role_id' => $roleId])
            ->count();
        if ($ret > 0) {
            return true;
        }

        return false;
    }

    public function getPermissionIds($userId)
    {
        $sql = "
            SELECT `permission_id` FROM `rbac_role_permissions`
            WHERE `role_id` IN(
              SELECT `role_id` FROM `rbac_user_roles` WHERE `user_id`=?
            )
        ";

        $statement = FDB::getPdo()->prepare($sql);
        $statement->execute([$userId]);
        $ret = $statement->fetchAll(\PDO::FETCH_ASSOC);

        if (empty($ret)) {
            return [];
        }

        return array_column($ret, 'permission_id');
    }

    public function getRoleIds($userId)
    {
        $ret = FDB::from('rbac_user_roles')
            ->where(['user_id' => $userId])
            ->fetchAll();

        if (empty($ret)) {
            return [];
        }
        return $ret;
    }
}
